<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/4
 * Time: 16:40
 */

namespace Home\Controller;
use DH16\Libs\Controller;
use DH16\Tools\Model;

/**
 * Class ClassController
 * @package Home\Controller
 * 班级管理控制器
 */
class ClassController extends Controller
{
    private $model;    //数据库对象

    /**
     * 构造方法,使用模型类操作数据
     */
    public function __construct()
    {
        /**
         * 实例化模型类
         */
        $this->model = new Model();
    }

    /**
     * 首页
     */
    public function index(){
        //2.获得所有班级信息
        $allClass = $this->model->query("select * from class");
        //3.分配变量
        $this->assign('allClass',$allClass);
        //1.载入模板
        $this->display();
    }

    /**
     * 添加班级
     */
    public function addClass(){
        //2.判断
        if(IS_POST){
            //3.获得班级
            $cname = $_POST['cname'];
            //6.验证：班级名重名
            $check = $this->model->query("select cname from class where cname='{$cname}'");
            if($check){
                $this->error('班级名已存在');
            }
            //4.添加数据
            $rows = $this->model->exec("insert into class set cname='{$cname}'");
            //5.提示信息
            if($rows){
                $this->success('添加成功','index.php?c=class&a=index');
            }else{
                $this->error('添加失败');
            }
        }
        //1.载入模板
        $this->display();
    }

    /**
     * 编辑班级
     */
    public function editClass(){
        //2.获取要编辑班级的id
        $cid = $_GET['cid'];
        //3.获取旧数据
        $oldClass = $this->model->query("select cname from class where cid={$cid}");
        $oldClass = $oldClass[0]['cname'];
        //4.分配变量
        $this->assign('oldClass',$oldClass);

        //5.判断
        if(IS_POST){
            //6.获取新数据
            $newClass = $_POST['cname'];
            //7.修改
            $rows = $this->model->exec("update class set cname='{$newClass}' where cid={$cid}");
            //8.提示信息
            if($rows){
                $this->success('编辑成功','index.php?c=class&a=index');
            }else{
                $this->error('编辑失败');
            }
        }
        //1.载入模板
        $this->display();
    }

    /**
     * 删除班级
     */
    public function deleteClass(){
        //1.获得要删除的班级id
        $cid = $_GET['cid'];
        //2.删除数据
        $rows = $this->model->exec("delete from class where cid={$cid}");
        //3.提示信息
        if($rows){
            $this->success('删除成功','index.php?c=class&a=index');
        }else{
            $this->error('删除失败');
        }
    }
}